#include "LinuxNetObject.h"

#include <QFile>
#include <QTextStream>
LinuxNetObject::LinuxNetObject(QObject *parent) : QObject(parent)
, old_upload(0)
, old_download(0)
{
    timer.setInterval(1000);

    connect(&timer, &QTimer::timeout, [=](){
        long upload = 0;
        long download = 0;

        QFile file("/proc/net/dev"); //  /proc/net/dev
        if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {  // 在读取时，把行尾结束符修改为 '\n'； 在写入时，把行尾结束符修改为本地系统换行风格，比如Windows文本换行是 "\r\n"
            return;
        }
        QTextStream stream(&file);
        QString line = stream.readLine();
        line  = stream.readLine();
        line  = stream.readLine();
        while (!line.isNull()) {
            line = line.trimmed();
            QStringList list = line.split(QRegExp("\\s{1,}"));   // 匹配任意 大于等于1个的 空白字符

            if (!list.isEmpty() && list.at(0).startsWith(m_devname)) {
                upload = list.at(9).toLong();
                download = list.at(1).toLong();
            }
            line  = stream.readLine();
        }
        file.close();
    
        emit updateNet(upload - old_upload, download - old_download);
        // QTextStream(stdout) << text << "\n";
        // QTextStream(stdout) << upload << "," << download << "\n";

        old_upload = upload;
        old_download = download;
    });
}


void LinuxNetObject::setDevName(const QString &name) {
    this->m_devname = name;
}

void LinuxNetObject::start() {
    timer.start();
}
void LinuxNetObject::stop() {
    timer.stop();
}

QStringList LinuxNetObject::getDevNames() {
    QStringList names;
    QFile file("/proc/net/dev"); //  /proc/net/dev
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {  // 在读取时，把行尾结束符修改为 '\n'； 在写入时，把行尾结束符修改为本地系统换行风格，比如Windows文本换行是 "\r\n"
        return names;
    }
    QTextStream stream(&file);
    QString line = stream.readLine();
    line  = stream.readLine();
    line  = stream.readLine();
    while (!line.isNull()) {
        line = line.trimmed();
        QStringList list = line.split(QRegExp("\\s{1,}"));   // 匹配任意 大于等于1个的 空白字符

        names << list.at(0);

        line  = stream.readLine();
    }
    file.close();

    return names;
}
